#include "musiclist.h"
#include<QMimeDatabase>
#include"music.h"
#include<QDebug>
#include<QSqlDatabase>
#include<QSqlError>
#include<QSqlQuery>
MusicList::MusicList()
{

}

void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
  for(auto e:urls)
  {
      // 由于添加进来的⽂件不⼀定是歌曲⽂件，因此需要再次筛选出⾳乐⽂件
      QMimeDatabase as;
      QMimeType ad=as.mimeTypeForFile(e.toLocalFile());
      QString ac=ad.name();
      qDebug()<<ac<<":"<<e;
      if(ad.name() == "audio/mpeg" || ad.name()== "audio/flac"||ad.name()=="audio.wav")
      {
          qDebug()<<e;
          Music af(e);
          this->musiclist.push_back(af);
      }
  }
}

iterator MusicList::begin()
{
    return musiclist.begin();
}

iterator MusicList::end()
{
    return musiclist.end();
}

iterator MusicList::findMusicById(const QString &musicId)
{
    for(auto it=musiclist.begin();it!=musiclist.end();it++)
    {
        if(it->getMusicId()==musicId)
        {
            return it;
        }
    }
    return end();
}

void MusicList::writeToDB()
{
    for(auto e:musiclist)
    {
        e.InsertMusicDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("SELECT musicId, musicName, musicSinger, albumName,\
                duration, musicUrl, isLike, isHistory\
                FROM musicInfo");
    QSqlQuery query;
    if(!query.exec(sql))
    {
        qDebug()<<"数据库查询失败";
        return;
    }
    while(query.next())
    {
        Music music;
        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setSingerName(query.value(2).toString());
        music.setAlbumName(query.value(3).toString());
        music.setDuration(query.value(4).toLongLong());
        music.setMusicUrl(query.value(5).toString());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());
        musiclist.push_back(music);
    }

}
